"use client";
import { useState, useEffect, useCallback } from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import CommonSelector from "@/components/CommonSelector";
import { format, addDays } from "date-fns";
import { useToast } from "@/components/ui/use-toast";
import { zhCN } from "date-fns/locale";
import { formatDateForAPI } from '@/lib/dateUtils'

export default function CourtBookingConfig({ lang, campuses, courts,createBookableTimeblocks, getBookableTimeblocks, deleteBookableTimeblock, deleteOrderByBlockId }) {
  const { toast } = useToast();
  const [selectedCampus, setSelectedCampus] = useState(campuses[0].id);
  const [selectedCourt, setSelectedCourt] = useState(courts[0].id);
  const [startDate, setStartDate] = useState(new Date());
  const [selectedTimeblocks, setSelectedTimeblocks] = useState([]);
  const [filteredCourts, setFilteredCourts] = useState([]);
  const [bookableTimeblocks, setBookableTimeblocks] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [price, setPrice] = useState(50); // 默认价格
  const [longPressTimer, setLongPressTimer] = useState(null); // 长按定时器
  const [isLongPress, setIsLongPress] = useState(false); // 是否是长按状态

  // 处理价格输入
  const handlePriceChange = (e) => {
    const value = e.target.value;
    // 允许空字符串或仅包含数字的字符串
    if (value === '' || /^\d+$/.test(value)) {
      setPrice(value === '' ? '' : Number(value));
    }
  };

  // 时间段列表
  const timeSlots = [
    "07:00", "07:30", "08:00", "08:30", "09:00", "09:30",
    "10:00", "10:30", "11:00", "11:30", "12:00", "12:30",
    "13:00", "13:30", "14:00", "14:30", "15:00", "15:30",
    "16:00", "16:30", "17:00", "17:30", "18:00", "18:30",
    "19:00", "19:30", "20:00", "20:30", "21:00", "21:30",
    "22:00", "22:30",
  ];

  // 生成一周的日期
  const days = Array.from({ length: 7 }, (_, i) => {
    const date = addDays(startDate, i);
    return {
      date,
      dayName: format(date, "EEEE",{ locale: zhCN }),
      dateString: format(date, "MM/dd")
    };
  });

  // 当校区改变时过滤球场
  useEffect(() => {
    if (selectedCampus) {
      const filteredCourts = courts.filter(court => court.branch_campus_id === selectedCampus);
      setFilteredCourts(filteredCourts);
      if (filteredCourts.length > 0) {
        setSelectedCourt(filteredCourts[0].id);
      } else {
        setSelectedCourt("");
      }
    } else {
      setFilteredCourts([]);
      setSelectedCourt("");
    }
  }, [selectedCampus, courts]);

  // 获取可配置时间段
  const fetchBookableTimeblocks = useCallback(async () => {
    if (!selectedCourt) return;

    setIsLoading(true);
    try {
      const startTimeFrom = format(startDate, "yyyy-MM-dd");
      const endTimeTo = format(addDays(startDate, 6), "yyyy-MM-dd");

      // 创建日期对象并设置时间
      const startDateObj = new Date(startTimeFrom);
      startDateObj.setHours(0, 0, 0, 0);

      const endDateObj = new Date(endTimeTo);
      endDateObj.setHours(23, 59, 59, 999);

      const timeblocks = await getBookableTimeblocks({
        court_id: selectedCourt,
        start_time_from: formatDateForAPI(startDateObj),
        end_time_to: formatDateForAPI(endDateObj),
      });
      console.log("可配置的时间段", timeblocks);

      setBookableTimeblocks(timeblocks);
    } catch (error) {
      console.error("Failed to fetch bookable timeblocks:", error);
      toast({
        title: "错误",
        description: "获取可配置时间段失败",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  }, [selectedCourt, startDate, toast, getBookableTimeblocks]);

  useEffect(() => {
    fetchBookableTimeblocks();
  }, [fetchBookableTimeblocks]);

  // 检查时间段是否已被配置
  const getTimeSlotStatus = (day, timeSlot) => {
    const dayStr = format(day.date, "yyyy-MM-dd");
    const [hour, minute] = timeSlot.split(":");

    // 使用新的日期格式化函数
    const date = new Date(day.date);
    date.setHours(parseInt(hour), parseInt(minute), 0);
    const startTime = formatDateForAPI(date);

    // 查找该时间段是否已存在
    const existingTimeblock = bookableTimeblocks.find(tb =>
      tb.start_time === startTime && tb.court_id === selectedCourt
    );

    if (existingTimeblock) {
      return {
        configured: true,
        id: existingTimeblock.id,
        price: existingTimeblock.price,
        status: existingTimeblock.status,
        isBooked: existingTimeblock.court_book_order_id !== null // 检查是否已被预约
      };
    }

    // 检查是否在当前选中的待添加时间段中
    const isPendingAdd = selectedTimeblocks.some(slot => {
      return slot.start_time === startTime && slot.court_id === selectedCourt;
    });

    return {
      configured: false,
      isPendingAdd
    };
  };

  // 切换选中状态
  const toggleTimeSlot = (day, timeSlot) => {
    const status = getTimeSlotStatus(day, timeSlot);

    if (status.configured) {
      if(status.status!=='booked') {
        // 直接删除
        deleteTimeblock(status.id);
        return;
      }else{
        // 取消用户订单,先询问下用户
        const confirm = window.confirm("确定取消该用户的预定吗？");
        if(confirm){
            deleteUserOrder(status.id);
        }
        return;
      }
    }

    const dayStr = format(day.date, "yyyy-MM-dd");
    const [hour, minute] = timeSlot.split(":");

    // 使用新的日期格式化函数
    const date = new Date(day.date);
    date.setHours(parseInt(hour), parseInt(minute), 0);
    const startTime = formatDateForAPI(date);

    // 计算结束时间 (假设每个时间段为30分钟)
    let endHour = parseInt(hour);
    let endMinute = parseInt(minute) + 30;

    if (endMinute >= 60) {
      endHour += 1;
      endMinute -= 60;
    }

    // 使用新的日期格式化函数
    const endDate = new Date(day.date);
    endDate.setHours(endHour, endMinute, 0);
    const endTime = formatDateForAPI(endDate);

    const timeSlotObj = {
      court_id: selectedCourt,
      start_time: startTime,
      end_time: endTime,
      price: price === '' ? 0 : parseInt(price),
      status: "active"
    };

    setSelectedTimeblocks(prev => {
      const exists = prev.some(
        slot => slot.start_time === startTime && slot.court_id === selectedCourt
      );

      if (exists) {
        return prev.filter(
          slot => !(slot.start_time === startTime && slot.court_id === selectedCourt)
        );
      } else {
        return [...prev, timeSlotObj];
      }
    });
  };

  // 删除时间段
  const deleteTimeblock = async (id) => {
    setIsLoading(true);
    try {
      await deleteBookableTimeblock(id);
      toast({
        title: "成功",
        description: "时间段已删除"
      });
      fetchBookableTimeblocks();
    } catch (error) {
      console.error("Failed to delete timeblock:", error);
      toast({
        title: "错误",
        description: "删除时间段失败"+error.message,
        variant: "destructive"
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 删除订单
  const deleteUserOrder = async (id) => {
    setIsLoading(true);
    try {
      await deleteOrderByBlockId(id);
      toast({
        title: "成功",
        description: "用户订单已删除"
      });
      fetchBookableTimeblocks();
    } catch (error) {
      console.error("Failed to delete order:", error);
      toast({
        title: "错误",
        description: "删除订单失败"+error.message,
        variant: "destructive"
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 保存设置
  const saveSettings = async () => {
    if (selectedTimeblocks.length === 0) {
      toast({
        title: "提示",
        description: "请先选择要添加的时间段"
      });
      return;
    }

    setIsLoading(true);
    try {
      await createBookableTimeblocks({
        timeblocks: selectedTimeblocks
      });

      toast({
        title: "成功",
        description: "时间段已开放，请等待用户预约"
      });

      // 刷新数据
      fetchBookableTimeblocks();
      setSelectedTimeblocks([]);
    } catch (error) {
      console.error("Failed to save timeblocks:", error);
      toast({
        title: "错误",
        description: "保存时间段失败",
        variant: "destructive"
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 前一周/后一周
  const goToPreviousWeek = () => {
    setStartDate(prev => addDays(prev, -7));
  };

  const goToNextWeek = () => {
    setStartDate(prev => addDays(prev, 7));
  };

  // 获取单元格颜色
  const getCellClass = (day, timeSlot) => {
    const status = getTimeSlotStatus(day, timeSlot);

    if (status.configured) {
      if (status.isBooked) {
        return 'bg-orange-200 hover:bg-orange-300'; // 已预约的时间段使用橙色
      }
      return 'bg-blue-200 hover:bg-blue-300'; // 已配置未预约的时间段使用蓝色
    }

    if (status.isPendingAdd) {
      return 'bg-green-200 hover:bg-green-300'; // 待添加的时间段使用绿色
    }

    return 'hover:bg-gray-100'; // 未配置的时间段保持原样
  };

  // 长按开始
  const handleDayHeaderMouseDown = (dayIndex) => {
    const timer = setTimeout(() => {
      setIsLongPress(true);
      selectAllTimeSlotsForDay(days[dayIndex]);
      toast({
        title: "已选择",
        description: `已选择 ${days[dayIndex].dateString} 全天时间段`
      });
    }, 500); // 500毫秒长按触发

    setLongPressTimer(timer);
  };

  // 长按结束
  const handleDayHeaderMouseUp = () => {
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      setLongPressTimer(null);
    }
    setIsLongPress(false);
  };

  // 鼠标离开
  const handleDayHeaderMouseLeave = () => {
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      setLongPressTimer(null);
    }
  };

  // 触摸开始 - 移动设备
  const handleDayHeaderTouchStart = (dayIndex, e) => {
    // 防止触发其他事件
    e.preventDefault();

    const timer = setTimeout(() => {
      setIsLongPress(true);
      selectAllTimeSlotsForDay(days[dayIndex]);
      // 触发振动反馈（如果设备支持）
      if (navigator.vibrate) {
        navigator.vibrate(100);
      }
      toast({
        title: "已选择",
        description: `已选择 ${days[dayIndex].dateString} 全天时间段`
      });
    }, 500); // 500毫秒长按触发

    setLongPressTimer(timer);
  };

  // 触摸结束 - 移动设备
  const handleDayHeaderTouchEnd = (e) => {
    e.preventDefault();
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      setLongPressTimer(null);
    }
    setIsLongPress(false);
  };

  // 触摸取消 - 移动设备
  const handleDayHeaderTouchCancel = (e) => {
    e.preventDefault();
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      setLongPressTimer(null);
    }
    setIsLongPress(false);
  };

  // 选择某天的所有时间段
  const selectAllTimeSlotsForDay = (day) => {
    const newTimeblocks = [...selectedTimeblocks];
    const dayStr = format(day.date, "yyyy-MM-dd");

    // 遍历所有时间段
    timeSlots.forEach(timeSlot => {
      const status = getTimeSlotStatus(day, timeSlot);

      // 如果已经配置或已在选中列表中，则跳过
      if (status.configured || status.isPendingAdd) {
        return;
      }

      const [hour, minute] = timeSlot.split(":");
      // 使用新的日期格式化函数
      const date = new Date(day.date);
      date.setHours(parseInt(hour), parseInt(minute), 0);
      const startTime = formatDateForAPI(date);

      // 计算结束时间 (假设每个时间段为30分钟)
      let endHour = parseInt(hour);
      let endMinute = parseInt(minute) + 30;

      if (endMinute >= 60) {
        endHour += 1;
        endMinute -= 60;
      }

      // 使用新的日期格式化函数
      const endDate = new Date(day.date);
      endDate.setHours(endHour, endMinute, 0);
      const endTime = formatDateForAPI(endDate);

      const timeSlotObj = {
        court_id: selectedCourt,
        start_time: startTime,
        end_time: endTime,
        price: price === '' ? 0 : parseInt(price),
        status: "active"
      };

      // 检查是否已经在选中列表中
      const exists = newTimeblocks.some(
        slot => slot.start_time === startTime && slot.court_id === selectedCourt
      );

      if (!exists) {
        newTimeblocks.push(timeSlotObj);
      }
    });

    setSelectedTimeblocks(newTimeblocks);
  };

  return (
    <div className="space-y-6 w-full">
      <h1 className="text-2xl font-bold">对外球场预约配置</h1>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader>
            <CardTitle>选择校区和场地</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>校区</Label>
              <CommonSelector
                name="campus"
                items={campuses.map(campus => ({ label: campus.name, value: campus.id }))}
                value={selectedCampus}
                onValueChange={setSelectedCampus}
              />
            </div>

            <div>
              <Label>场地</Label>
              <CommonSelector
                name="court"
                items={filteredCourts.map(court => ({ label: court.name, value: court.id }))}
                value={selectedCourt}
                onValueChange={setSelectedCourt}
                disabled={!selectedCampus}
              />
            </div>

            <div>
              <Label>价格 (元/30分钟)</Label>
              <Input
                type="text"
                value={price}
                onChange={handlePriceChange}
                min={0}
                inputMode="numeric"
                pattern="[0-9]*"
              />
            </div>
          </CardContent>
        </Card>

        <Card className="md:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>配置可预约时间</CardTitle>
            <div className="flex space-x-2">
              <Button onClick={goToPreviousWeek} variant="outline" size="sm">上一周</Button>
              <Button onClick={goToNextWeek} variant="outline" size="sm">下一周</Button>
            </div>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex justify-center py-8">加载中...</div>
            ) : !selectedCourt ? (
              <div className="flex justify-center py-8">请先选择校区和场地</div>
            ) : (
              <>
                <div className="overflow-x-auto pb-16 md:pb-0">
                  <table className="w-full border-collapse">
                    <thead>
                      <tr>
                        <th className="border p-2">时间</th>
                        {days.map((day, idx) => (
                          <th
                            key={idx}
                            className="border p-1 text-xs cursor-pointer hover:bg-gray-100"
                            onMouseDown={() => handleDayHeaderMouseDown(idx)}
                            onMouseUp={handleDayHeaderMouseUp}
                            onMouseLeave={handleDayHeaderMouseLeave}
                            onTouchStart={(e) => handleDayHeaderTouchStart(idx, e)}
                            onTouchEnd={handleDayHeaderTouchEnd}
                            onTouchCancel={handleDayHeaderTouchCancel}
                          >
                            {day.dateString}<br />
                            {day.dayName}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {timeSlots.map((timeSlot, idx) => (
                        <tr key={idx}>
                          <td className="border p-1 text-xs">{timeSlot}</td>
                          {days.map((day, dayIdx) => (
                            <td
                              key={dayIdx}
                              className={`border p-1 text-center text-xs cursor-pointer ${getCellClass(day, timeSlot)}`}
                              onClick={() => toggleTimeSlot(day, timeSlot)}
                            >
                              {getTimeSlotStatus(day, timeSlot).configured
                                ? getTimeSlotStatus(day, timeSlot).isBooked
                                  ? '已预约'
                                  : `¥${getTimeSlotStatus(day, timeSlot).price}`
                                : getTimeSlotStatus(day, timeSlot).isPendingAdd
                                  ? '待添加'
                                  : ''}
                            </td>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                <div className="p-2 sticky bottom-0 w-full bg-white mt-4 shadow-md flex justify-between items-center">
                  <div className="text-xs">
                    <span className="inline-block w-4 h-4 bg-blue-200 mr-1"></span> 已开放
                    <span className="inline-block w-4 h-4 bg-orange-200 ml-4 mr-1"></span> 已预约
                    <span className="inline-block w-4 h-4 bg-green-200 ml-4 mr-1"></span> 待添加
                  </div>

                  {selectedTimeblocks.length > 0 && (
                    <div className="text-xs font-bold">
                      已选择 {selectedTimeblocks.length} 个时间段
                    </div>
                  )}

                  <Button
                    onClick={saveSettings}
                    disabled={isLoading || selectedTimeblocks.length === 0}
                  >
                    保存配置
                  </Button>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}